import Vue from 'vue'
import Vuex from 'vuex'
import http from '../http'
import VuexPersistence from 'vuex-persist'

Vue.use(Vuex)
// 吧频道存储在key：vuex  里面
const vuexLocal = new VuexPersistence({
  storage: window.localStorage,
  reducer: (state) => ({ cateList: state.cateList })
})
export default new Vuex.Store({
  state: {
    // 频道分类数组
    cateList: []
  },
  mutations: {
    initData(state, list) {
      // 给 每一个 item 动态的添加一个属性 是否选中
      list.forEach(item => {
        // item.selected=true
        Vue.set(item, "selected", true)
      });
      let storage = JSON.parse(localStorage.getItem('vuex'))
      if (storage && storage.cateList) {
        state.cateList = storage.cateList
        return
      }
      state.cateList = list
    },
    changeState(state, id) {
      state.cateList.forEach(item => {
        if (item.id == id) {
          item.selected = !item.selected
          return
        }
      })
    }
  },
  actions: {
    getData({ commit }) {
      http("/getCategroy", "get").then(res => {
        console.log(123);
        console.log(res);
        commit("initData", res.result)
      }).catch(err => {
        console.log(err);
      })
    }
  },
  getters: {
    getSelectedCate(state) {
      return state.cateList.filter(item => {
        return item.selected == true
      })
    },
    getUnSelectedCate(state) {
      return state.cateList.filter(item => {
        return item.selected == false
      })
    },
  },
  modules: {
  },
  plugins: [vuexLocal.plugin]
})